import axios from "axios";
import store from '@/store'
import { Message } from 'element-ui'
import router from '@/router'
const service = axios.create({
    baseURL: process.env.VUE_APP_BASE_API,//基础地址，根据环境不同设置不同的基础地址
    timeout: 10000,
})

service.interceptors.request.use((config) => {
    if (store.getters.token) {
        config.headers.Authorization = `Bearer ${store.getters.token}`
    }
    return config
}, (error) => {
    return Promise.reject(error)
})

service.interceptors.response.use((response) => {
    if (response.data instanceof Blob) {
        return response.data
    }
    const { message, data, code } = response.data  // 默认json格式
    if (code === 200) {
        return data
    } else {
        Message({ type: 'error', message })
        return Promise.reject(new Error(message))
    }
}, async (error) => {
    if (error.response.status === 401) {
        Message({ type: 'warning', message: 'token超时，请重新登录' })
        await store.dispatch('user/logOut')
        router.push('/login')
        return Promise.reject(error)
    }
    Message({ type: 'error', message: error.message })
    return Promise.reject(error)
})

export default service